package com.wx.servlet;

import com.wx.entry.SmbmsUser;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("userName");
        System.out.println(name);
        String pwd = req.getParameter("userPwd");
        System.out.println(pwd);
        //去smbms 数据库里 smbms_user表 查找用户
        //  JDBC 技术
        try {
            //第一步，加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //第二步 获得连接
            String url = "jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8";
            String userRoot = "root";
            String userPwd = "wxok";
            Connection connection = DriverManager.getConnection(url, userRoot, userPwd);
            String sql = "select * from smbms_user where userCode = '"+name+"'";
            PreparedStatement pst = connection.prepareStatement(sql);
            ResultSet resultSet = pst.executeQuery();
            SmbmsUser smbmsUser  = null;
            //取数据库当中的数据赋值 smbmsUser
            while (resultSet.next()){
                smbmsUser = new SmbmsUser();
                String userCode =    resultSet.getString("userCode");
                String userName =     resultSet.getString("userName");
                String userPassword =     resultSet.getString("userPassword");
                //重数据库里查出的数据，赋值Java类对象
                smbmsUser.setUserCode(userCode);
                smbmsUser.setUserName(userName);
                smbmsUser.setUserPassword(userPassword);
            }
            //判断数据库中的值和页面的值是否相等。
            if(smbmsUser!=null){
                //用户名称存在
                if(smbmsUser.getUserPassword().equals(pwd)){
                    //用户密码也相等
                    HttpSession session = req.getSession();
                    session.setAttribute("userName",smbmsUser.getUserName());
                    resp.sendRedirect("home.jsp");
                }else {
                    resp.sendRedirect("login.jsp?error=1");
                }
            }else{
                resp.sendRedirect("login.jsp?error=1");
            }
            //先根据用户名，查出是否存在
            //如果存在，在对比密码是否相等。
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }



    }
}
